<template>
  <el-scrollbar class="container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="160px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input v-model="queryParams.templateName" clearable></el-input>
      </el-form-item>
      <el-form-item label="地震阈值" prop="seismicThreshold">
        <el-input v-model="queryParams.seismicThreshold" clearable></el-input>
      </el-form-item>
      <el-form-item label="使用状态" prop="status">
        <el-select v-model="queryParams.status" clearable>
          <el-option v-for="item in onState" :key="item.value" :label="item.name" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
        <el-select v-model="queryParams.templateType" clearable>
          <el-option v-for="item in templateType" :key="item.value" :label="item.name" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" ">
        <el-button type="primary" @click="getPlot">查询</el-button>
        <el-button plain @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-divider ref="divider"></el-divider>

    <el-row :gutter="10" class="mb8" style="float:left">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="mapSettings">出图设置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="Delete" @click="batchDelete">批量删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dataList" ref="table" @selection-change="selectChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="地震阈值" align="center" prop="seismicThreshold">
        <template #default="{ row }">
          <span>{{ row.seismicThreshold }}级</span>
        </template>
      </el-table-column>
      <el-table-column label="制图范围" align="center" prop="range">
        <template #default="{ row }">
          <span>{{ row.range }}km</span>
        </template>
      </el-table-column>
      <el-table-column label="国境内外" align="center" prop="insideAndOutside">
        <template #default="{ row }">
          <span>{{ range.find(item => item.value === row.insideAndOutside)?.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="范围" align="center" prop="borderArea">
        <template #default="{ row }">
          <span v-if="row.insideAndOutside == '0'">
            {{ country.filter(item => row.borderArea.includes(item.value)).map(item => item.name).join(',') }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="status">
        <template #default="{ row }">
          <span>{{ onState.find(item => item.value === row.status)?.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板类型" align="center" prop="templateType">
        <template #default="{ row }">
          <span>{{ templateType.find(item => item.value == row.templateType)?.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createUsername" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="viewItem(row)">查看</el-button>
          <el-button type="text" @click="useItem(row)" v-if="row.status == '0'">使用</el-button>
          <el-button type="text" @click="deleteItem(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination style="margin-top: 15px" v-show="queryParams.total > 0" :total="queryParams.total"
      v-model:page="queryParams.page" v-model:limit="queryParams.rows" @pagination="getPlot" ref="pagination" />

    <!-- 出图设置 -->
    <el-dialog v-model="mappingTypeDialog" title="请选择" width="500px" @close="cancelMappingType">
      <el-form :model="mappingTypeForm" label-width="100px" ref="mappingTypeRef">
        <el-form-item label="图件类型" prop="templateType">
          <el-radio-group v-model="mappingTypeForm.templateType">
            <el-radio v-for="item in templateType" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="openMapping">确定</el-button>
        <el-button plain @click="cancelMappingType">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="mappingDialog" width="520px" @close="cancelMapping">
      <template #title>
        <svg-icon icon-class="list"></svg-icon>
        <span style="padding: 0 10px">{{ mappingTitle }}</span>
      </template>
      <el-form :model="mappingForm" label-width="100px" ref="mappingRef" :rules="mappingRules" scroll-to-error
        :disabled="isDisabled">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="mappingForm.templateName"></el-input>
        </el-form-item>
        <el-form-item label="制图范围" prop="range">
          <el-input v-model="mappingForm.range" placeholder="以发震地点为中心" style="width: 95%;padding-right: 10px"></el-input>
          <span>km</span>
        </el-form-item>
        <el-form-item label="地震阈值" prop="seismicThreshold">
          <el-input v-model="mappingForm.seismicThreshold" placeholder="结果保留一位小数"
            style="width: 95%;padding-right: 10px"></el-input>
          <span>级</span>
        </el-form-item>
        <el-form-item label="国境内外" prop="insideAndOutside">
          <el-radio-group v-model="mappingForm.insideAndOutside" @change="insideAndOutsideChange">
            <el-radio v-for="item in range" :key="item.value" :label="item.value">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="范围" prop="borderArea" v-if="mappingForm.insideAndOutside === '0'">
          <el-checkbox-group v-model="mappingForm.borderArea">
            <el-checkbox v-for="item in country" :key="item.value" :label="item.value">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="抓取频率" prop="frequency">
          <el-input v-model.number="mappingForm.frequency" placeholder="请输入整数">
            <template #append>
              <el-select v-model.number="mappingForm.unit" placeholder="请选择单位" style="width: 115px">
                <el-option label="天" value="天" />
                <el-option label="时" value="时" />
                <el-option label="分" value="分" />
                <el-option label="秒" value="秒" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveMapping" v-if="isSave">保存</el-button>
        <el-button plain @click="cancelMapping">取消</el-button>
      </template>
    </el-dialog>
  </el-scrollbar>
</template>
<script setup>
import { templateType, onState, country, range } from '@/views/quickMapping/common/const'
import { savePlot, getAllPlot, operate, getById, updatePlot, deletePlot, duplicateCheck } from '@/api/quickMapping/dataManage/plotSettings'

const { proxy } = getCurrentInstance()
const queryParams = ref({
  page: 1,
  rows: 10,
  total: 0
})
const loading = ref(false)
const dataList = ref([])
const isDisabled = computed(() => !!(mappingForm.value.status && mappingForm.value.status !== '0'))
const isSave = computed(() => !mappingForm.value.status || mappingForm.value.status == '0')
// 重置
const resetQuery = () => {
  queryParams.value.page = 1
  proxy.resetForm('queryRef')
  getPlot()
}
// 多选
const ids = ref([])
const selectChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 批量删除
const batchDelete = () => {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  proxy.$modal.confirm(`是否确定删除?`).then(() => {
    return deletePlot(ids.value)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    getPlot()
  })
}

const getPlot = () => {
  getAllPlot(queryParams.value).then(res => {
    queryParams.value.total = res.data.total
    dataList.value = res.data.rows
  })
}
// 出图设置
const mappingTitle = ref('')
const mapSettings = () => {
  mappingTypeDialog.value = true
  mappingTitle.value = templateType.find(item => item.value === mappingTypeForm.value.templateType).name + '出图设置'
}
const mappingTypeDialog = ref(false)
const mappingTypeForm = ref({ templateType: '0' })
const cancelMappingType = () => {
  mappingTypeDialog.value = false
  proxy.resetForm('mappingTypeRef')
}
const openMapping = () => {
  mappingTypeDialog.value = false
  mappingDialog.value = true
  if (mappingForm.value.templateType) {
    mappingTitle.value = templateType.find(item => item.value === mappingForm.value.templateType).name + '出图设置'
  }
  nextTick(() => {
    proxy.$refs.mappingRef.clearValidate()
  })
  mappingForm.value.templateType = mappingTypeForm.value.templateType
}
const mappingDialog = ref(false)
const initMappingForm = () => ({ borderArea: [] })
const mappingForm = ref(initMappingForm())
const templateNameRepeat = (rule, value, cb) => {
  duplicateCheck(value, mappingForm.value.id).then(res => {
    if (res.data === '0') {
      cb()
    } else {
      cb(new Error('模板名称重复！'))
    }
  })
}
const mappingRules = {
  templateName: [{ validator: templateNameRepeat, trigger: 'blur' }],
  seismicThreshold: [
    { required: true, message: '请填写地震阈值！', trigger: 'blur' },
    { pattern: /^(([1-9]+\d*)|(0{1}))(.[0-9]{0,1})?$/, message: '保留一位小数' }
  ],
  insideAndOutside: [{ required: true, message: '请填写国境内外！', trigger: 'change' }],
  borderArea: [{ required: true, message: '请填写范围！', trigger: 'change' }],
}
const cancelMapping = () => {
  mappingDialog.value = false
  proxy.resetAllForm(mappingForm.value, initMappingForm())
  proxy.resetForm('mappingTypeRef')
}
const insideAndOutsideChange = val => {
  if (val == '1') {
    mappingForm.value.borderArea = ''
  }else{
    mappingForm.value.borderArea = []
  }
}
// 出图设置-保存、修改
const saveMapping = () => {
  proxy.$refs['mappingRef'].validate(valid => {
    if (valid) {
      if (mappingForm.value.borderArea.length > 0) {
        mappingForm.value.borderArea = mappingForm.value.borderArea.join(',')
      }
      if (mappingForm.value.id) {
        updatePlot({ ...mappingForm.value }).then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('修改成功！')
            cancelMapping()
            getPlot()
          }
        })
      } else {
        savePlot({ ...mappingForm.value }).then(res => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess('保存成功！')
            cancelMapping()
            getPlot()
          }
        })
      }
    }
  })
}
// 查看
const viewItem = row => {
  getById(row.id).then(res => {
    mappingTypeForm.value.templateType = row.templateType
    mappingTitle.value = templateType.find(item => item.value === row.templateType).name
    mappingDialog.value = true
    mappingForm.value = res.data
    mappingForm.value.borderArea = mappingForm.value.borderArea.split(',')
  })
}
// 使用
const useItem = (row) => {
  let type = templateType.find(item => item.value === row.templateType).name
  proxy.$modal.confirm(`确定更换【${type}】模板?`).then(() => {
    return operate(row)
  }).then(() => {
    proxy.$modal.msgSuccess('更换成功！')
    getPlot()
  })
}
// 删除
const deleteItem = (row) => {
  proxy.$modal.confirm(`是否确定删除${row.templateName}?`).then(() => {
    return deletePlot(row.id)
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    getPlot()
  })
}

defineExpose({
  getPlot
})
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  min-height: 400px;
  overflow: auto;
}
</style>